package com.enlorenz.core.engine.manager;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.enlorenz.core.engine.EngineUtils;
import com.enlorenz.core.engine.IEngine;
import com.enlorenz.core.engine.exception.EngineControlException;

/**
 * 引擎管理者，用于集中管理引擎的启动，停止，和重启等功能
 * @author lcb
 */
public class EngineManager {
	protected Logger logger=LoggerFactory.getLogger(this.getClass());
	private List<IEngine> engines;
	private EngineCheckThread engineCheck=new EngineCheckThread();
	private Boolean checkedLog=true;
	//检测线程间隔时间
	private long checkThreadSleepTime=60000;
	
	/**
	 * 初始化
	 */
	public void init(){
		long allSt=System.currentTimeMillis();
		engineCheck.setEngines(engines);
		engineCheck.setCheckLog(checkedLog);
		engineCheck.setName("线程检查");
		engineCheck.setSleepTime(checkThreadSleepTime);
		engineCheck.init();
		engineCheck.start();
		long allEd=System.currentTimeMillis();
		logger.info("启动线程检查功能,COST[{}]ms",String.valueOf((allEd-allSt)));
	}
	
	/**
	 * 关闭所有的引擎
	 * @throws EngineControlException
	 */
	public void stopEngines() throws EngineControlException{
		logger.info("开始关闭引擎列表");
		EngineUtils.stopEngineList(engines);
		EngineUtils.shutdown(engineCheck);
		logger.info("结束关闭引擎列表");
		
	}
	
	/**
	 * 启动引擎列表
	 * @throws EngineControlException
	 */
	public void startEngines() throws EngineControlException{
		logger.info("*********线程启动管理开始***********************");
		long allSt=System.currentTimeMillis();
		for(IEngine engine:engines){
			startEngine(engine);
		}
		long allEd=System.currentTimeMillis();
		logger.info("*********线程启动管理结束,用时[{}]毫秒*********",String.valueOf((allEd-allSt)));
	}
	/**
	 * 启动引擎
	 * @param engine
	 * @throws EngineControlException
	 */
	public void startEngine(IEngine engine) throws EngineControlException{
		logger.info("----启动线程[{}]开始",engine.getName());
		long st=System.currentTimeMillis();
		engine.init();
		engine.start();
		long ed=System.currentTimeMillis();
		logger.info("----启动线程[{}]结束,用时[{}]毫秒",engine.getName(),String.valueOf(ed-st));
	}
	
	
	public long getCheckThreadSleepTime() {
		return checkThreadSleepTime;
	}

	public void setCheckThreadSleepTime(long checkThreadSleepTime) {
		this.checkThreadSleepTime = checkThreadSleepTime;
	}

	public void setEngines(List<IEngine> engines) {
		this.engines = engines;
	}

	public void setEngineCheck(EngineCheckThread engineCheck) {
		this.engineCheck = engineCheck;
	}

	public List<IEngine> getEngines() {
		return engines;
	}

	public void setCheckedLog(Boolean checkedLog) {
		this.checkedLog = checkedLog;
	}
	
}
